<?php
namespace app\wchat\controller;

use think\Controller;
use think\Db;
use think\Session;

class Oauth extends Controller
{
    protected $appid,$appsecret,$shop_id,$tore_id;

	/**
     * 构造方法
     */
    public function __construct()
    {
        parent::__construct();

        // 接收参数
        $input = input();

        // 参数shop_id为店铺ID
        if($input['shop_id'] > 0){

        	$shop_info = Db("shops")->where('shop_id',input('shop_id'))->find();

            Session::set("shop_id",$shop_info['shop_id']);

        	$this->appid 	= $shop_info['appid'];
        	$this->appsecret= $shop_info['appsecret'];
        	dump("++++++".$this->appid);echo "<br>";

        }else{

            die("非法访问");

        }

    }


    /**
     * 请求微信服务器获取用户信息
     */
    public function getWxInfo()
    {

        $input = input();
        // 回调地址必填
        if(!input("call_back")){
            $this->error("回调地址参数不完整");
        }

        // 参数整理
        $params = http_build_query($input);

        $redirecturl = urlencode(request()->domain() . url("wchat/oauth/getInfo") . "?{$params}");

//        $redirecturl = urlencode(request()->domain().url('wchat/oauth/getInfo')."?".$params."&std=1");

        $snsapi_userInfo_url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$this->appid}&redirect_uri={$redirecturl}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
        // 跳转
        $this->redirect($snsapi_userInfo_url);
    }


    /**
     * 获取用户信息
     */
    public function getInfo()
    {
        $code = input('code');

        if(isset($code)){
            // 通过code换取网页授权access_token
            $curl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appid}&secret={$this->appsecret}&code={$code}&grant_type=authorization_code";
            $content = file_get_contents($curl);
            $result = json_decode($content,true);

            // 通过access_token和openid拉取用户信息
            $webAccess_token    = $result['access_token'];

            dump($webAccess_token);
            echo "<br>";

            $openid             = $result['openid'];

            dump($openid);
            echo "<br>";

            $userInfourl = "https://api.weixin.qq.com/sns/userinfo?access_token={$webAccess_token}&openid={$openid}&lang=zh_CN";

            dump($userInfourl);
            echo "<br>";

            // 用户信息在此
            $recontent = file_get_contents($userInfourl);


            dump($recontent);
            echo "<br>";

            // 回信地址
            $url = input('call_back') . "?back_info={$recontent}";
            var_dump($result);

            // 邮寄信息
            $this->redirect($url);

        }
    }


}
